import React, { useState, useEffect } from 'react';
import { Avatar, Empty, List, Spin, Icon } from 'antd';
import InfiniteScroll from 'react-infinite-scroller';
import _ from 'lodash';
import { eventTrack } from '@/utils/track';
import { formatDate, formatEmployee } from '../utils';
import styles from './styles.less';
import { useAvatarUrl, useDeleteMail } from '../hooks';

// 邮件列表
const MailingList = ({
    data,
    curData = [],
    onLoadMore,
    hasMore,
    onClick,
    query = {},
    defaultId = null,
    setDefaultId,
    setSourceData,
    setReadParams
}) => {
    // 取出邮件列表
    const [mailList, setMailList] = useState([]);

    useEffect(() => {
        // 监听当前拉取的数据列表，返回邮箱地址数组
        if (curData.length > 0) {
            // 获取收件列表的邮箱
            let arr = [];
            curData.forEach(item => {
                arr = [...arr, ...item.receiverList.split(',')];
            });
            setMailList(_.uniq([...mailList, ...curData.map(item => item.sender), ...arr]));
        }
    }, [curData]);

    // 通过邮件列表拉取头像
    const { resData: avatarList } = useAvatarUrl(mailList);

    // 这个只是因为eslint格式化长度问题一直提示错误提取的方法，╮(╯▽╰)╭
    const avaturl = value => formatEmployee(avatarList, value).url;

    // 点击或者右键回调
    const handleClick = e => {
        const { id, readFlag, subject } = e;
        // 设置打开的id
        setDefaultId(id);

        // 打开详情回调
        onClick({
            id,
            readFlag,
            subject
        });

        // 埋点
        if (query.mailType === 'in') {
            eventTrack({
                eventName: 'personal_message_mails_inbox_info_click',
                pageName: 'personal_message_mails',
                eventProps: { click_context: subject }
            });
        } else {
            eventTrack({
                eventName: 'personal_message_mails_outbox_info_click',
                pageName: 'personal_message_mails',
                eventProps: { click_context: subject }
            });
        }
    };

    // ==================右键菜单==================
    const [deleteParams, setDeleteParams] = useState(null);
    const [delLoading, delResResult, delSetResData] = useDeleteMail(deleteParams); // 删除邮件

    const delMail = id => {
        const obj = {
            belongs: query.belongs,
            password: query.password,
            id
        };
        setDeleteParams({ ...obj });
    };

    // const handleMenuClick = e => {
    //     // 删除邮件
    //     if (e.key === 'delete') {
    //         delMail(defaultId);
    //     }
    // };

    const handleDelItemClick = (e, id, readFlag) => {
        e.stopPropagation();
        delMail(id);
        // 未读更改状态
        if (readFlag === 0) {
            setReadParams({
                belongs: query.belongs,
                id
            });

            // 更改本地数据中相关id的阅读状态
            setSourceData(
                data.map(item => {
                    const temp = item;
                    if (item.id === id) {
                        temp.readFlag = 1;
                    }
                    return temp;
                })
            );
        }
    };

    // 监听删除结果
    useEffect(() => {
        if (delResResult && delResResult === 'ok') {
            // 更新数据源
            setSourceData([...data.filter(item => item.id !== deleteParams.id)]);
            // 清空详情id，删除结果，删除参数等
            setDefaultId(null);
            setDeleteParams(null);
            delSetResData(null);
        }
    }, [delResResult]);

    // 暂时禁用右键删除
    // const menu = (
    //     <Menu onClick={handleMenuClick} style={{ width: 100 }}>
    //         <Menu.Item key="delete">删除</Menu.Item>
    //     </Menu>
    // );
    // ================= end  ===================

    return (
        <div className={styles.mailingListWrap}>
            {data.length > 0 ? (
                <InfiniteScroll
                    threshold={50}
                    initialLoad={false}
                    loadMore={onLoadMore}
                    pageStart={1}
                    hasMore={hasMore}
                    useWindow={false}
                >
                    <List
                        dataSource={data}
                        split={false}
                        renderItem={item => (
                            <Spin spinning={delLoading && item.id && item.id === deleteParams.id}>
                                <List.Item
                                    className={`${styles.listItem} ${item.id === defaultId && styles.itemActive}`}
                                    onClick={() => {
                                        handleClick(item);
                                    }}
                                    extra={
                                        <>
                                            <div className={styles.extraDate}>{formatDate(item.sendDate)}</div>
                                            {!delLoading && (
                                                <div
                                                    className={styles.extraDelete}
                                                    onClick={e => handleDelItemClick(e, item.id, item.readFlag)}
                                                >
                                                    <Icon type="close-circle" />
                                                </div>
                                            )}
                                        </>
                                    }
                                >
                                    <List.Item.Meta
                                        className={item.readFlag === 0 ? styles.unread : ''}
                                        avatar={
                                            <div style={{ paddingLeft: 24 }}>
                                                {query.mailType === 'in' ? (
                                                    <i
                                                        className={`${styles.mailStatusIcon} ${
                                                            item.readFlag === 0 ? styles.unReadIco : ''
                                                        }`}
                                                    ></i>
                                                ) : (
                                                    <Icon type="check" className={styles.mailStatusCheck} />
                                                )}
                                                <Avatar
                                                    icon="user"
                                                    size={40}
                                                    src={
                                                        // 如果是收件箱，默认显示第一个收件人头像
                                                        query.mailType === 'in'
                                                            ? avaturl(item.sender)
                                                            : avaturl(item.receiverList.split(',')[0])
                                                    }
                                                />
                                            </div>
                                        }
                                        title={
                                            <>
                                                {query.mailType === 'in' ? (
                                                    <span title={formatEmployee(avatarList, item.sender).name}>
                                                        {formatEmployee(avatarList, item.sender).name}
                                                    </span>
                                                ) : (
                                                    <span
                                                        title={
                                                            !_.isEmpty(item.receiverList) &&
                                                            item.receiverList
                                                                .split(',')
                                                                .map(sitem => formatEmployee(avatarList, sitem).name)
                                                        }
                                                    >
                                                        {!_.isEmpty(item.receiverList) &&
                                                            item.receiverList.split(',').map((sitem, index) => {
                                                                const arr = item.receiverList.split(',');
                                                                return `${formatEmployee(avatarList, sitem).name}${
                                                                    arr.length > 1 && index !== arr.length - 1
                                                                        ? '，'
                                                                        : ''
                                                                }`;
                                                            })}
                                                    </span>
                                                )}
                                            </>
                                        }
                                        description={<span title={item.subject}>{item.subject}</span>}
                                    />
                                </List.Item>
                            </Spin>
                        )}
                    />
                </InfiniteScroll>
            ) : (
                <div className={styles.emptyDataWrap}>
                    <Empty
                        description="暂无邮件列表"
                        imageStyle={{ marginBottom: 16 }}
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                    />
                </div>
            )}
        </div>
    );
};
export default MailingList;
